/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.momarketing.service;

import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.boxin.ims.modules.momarketing.entity.MicroPage;
import com.boxin.ims.modules.momarketing.dao.MicroPageDao;

/**
 * 微网页Service
 * @author Jakemanse
 * @version 2013-11-22
 */
@Component
@Transactional(readOnly = true)
public class MicroPageService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(MicroPageService.class);
	
	@Autowired
	private MicroPageDao microPageDao;
	
	public MicroPage get(Long id) {
		return microPageDao.findOne(id);
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-11-22  上午12:29:16
	 * @function <p> 微网站下的所有微网页  </p>
	 * @param projectId
	 * @return
	 */
	public List<MicroPage> findMicropagesByProjectId(Long projectId){
		DetachedCriteria dc = microPageDao.createDetachedCriteria();
		if(projectId!=null && projectId>0){
			dc.createAlias("project", "project");
			dc.add(Restrictions.eq("project.id", projectId));
		}
		dc.addOrder(Order.desc("sort"));
		return microPageDao.find( dc);
	}
	
	
	public Page<MicroPage> find(Page<MicroPage> page, MicroPage microPage) {
		DetachedCriteria dc = microPageDao.createDetachedCriteria();
		if (microPage.getUser()!=null && microPage.getUser().getId()>0){
			dc.add(Restrictions.eq("user.id", microPage.getUser().getId()));
		}
		
		if(microPage.getProject()!=null && microPage.getProject().getId()>0){
			dc.createAlias("project", "project");
			dc.add(Restrictions.eq("project.id", microPage.getProject().getId()));
		}
		if (StringUtils.isNotEmpty(microPage.getName())){
			dc.add(Restrictions.like("name", "%"+microPage.getName()+"%"));
		}
		dc.addOrder(Order.desc("sort"));
		return microPageDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(MicroPage microPage) {
		microPage.setContent(StringEscapeUtils.unescapeHtml4(microPage.getContent()) );
		microPageDao.save(microPage);
	}
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		microPageDao.deleteById(id);
	}
	
}
